package com.cn.ryc.service;

import com.cn.ryc.mapper.UserMapper;
import com.cn.ryc.model.User;
import com.cn.ryc.util.ApiResponse;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AuthService {

    @Autowired
    private UserMapper userMapper;

    private final Key jwtSecretKey = Keys.secretKeyFor(SignatureAlgorithm.HS512); // 生成安全的密钥
    private final long jwtExpirationMs = 86400000; // 1天

    // 登录方法
    public ResponseEntity<ApiResponse<Map<String, Object>>> login(User user) {
        try {
            // 根据用户名查找用户
            User foundUser = userMapper.findByUsername(user.getUsername());
            // 如果用户存在且密码正确
            if (foundUser != null && foundUser.getPassword().equals(user.getPassword())) {
                // 生成JWT token
                String token = generateJwtToken(foundUser);
                // 构造返回数据
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("token", token);
                responseData.put("user", foundUser.toResponseDTO());
                // 返回成功响应
                return ResponseEntity.ok(ApiResponse.success(responseData));
            }
            // 返回401错误响应
            return ResponseEntity.status(401).body(ApiResponse.error(401, Map.of("message", "用户名或密码错误")));
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 返回500错误响应
            return ResponseEntity.status(500).body(ApiResponse.error(500, Map.of("message", "服务器内部错误")));
        }
    }

    // 生成JWT token方法
    private String generateJwtToken(User user) {
        return Jwts.builder()
                .setSubject(user.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
                .signWith(jwtSecretKey)
                .compact();
    }

    // 注册方法
    public ResponseEntity<ApiResponse<Map<String, Object>>> register(User user) {
        try {
            if (userMapper.existsByUsername(user.getUsername())) {
                return ResponseEntity.status(400).body(ApiResponse.error(400, Map.of("message", "用户名已存在")));
            }

            if (!user.getPassword().equals(user.getConfirmPassword())) {
                return ResponseEntity.status(400).body(ApiResponse.error(400, Map.of("message", "密码和确认密码不一致")));
            }
            userMapper.insertUser(user);
            return ResponseEntity.ok(ApiResponse.success(Map.of("message", "注册成功")));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(ApiResponse.error(500, Map.of("message", "服务器内部错误")));
        }
    }

    // 检查用户名是否存在方法
    public ResponseEntity<ApiResponse<Map<String, Object>>> checkUsername(String username) {
        System.out.println(username);
        boolean exists = userMapper.existsByUsername(username);
        System.out.println(exists);
        return ResponseEntity.ok(ApiResponse.success(Map.of("exists", exists)));
    }

    // 获取所有用户方法
    public ResponseEntity<ApiResponse<List<User>>> getAllUser() {
        return ResponseEntity.ok(ApiResponse.success(userMapper.getAllUser()));
    }

    public ResponseEntity<ApiResponse<String>> updateUser(User user) {
        try {
            userMapper.updateUser(user);
            return ResponseEntity.ok(ApiResponse.success("更新成功"));
        }
        catch (Exception e) {
            return ResponseEntity.status(500).body(ApiResponse.error(500,"服务器内部错误"));
        }
    }

    public ResponseEntity<ApiResponse<String>> updatePassword(User user) {
        // 尝试更新密码
        try {
            // 调用userMapper的updatePassword方法更新密码
            userMapper.updatePassword(user);
            // 返回更新成功的响应
            return ResponseEntity.ok(ApiResponse.success("更新成功"));
        }
        catch (Exception e) {
            // 捕获异常，返回服务器内部错误的响应
            return ResponseEntity.status(500).body(ApiResponse.error(500,"服务器内部错误"));
        }
    }

    public ResponseEntity<ApiResponse<User>> getUserById(Long id) {
            User user = userMapper.getUserById(id);
            return ResponseEntity.ok(ApiResponse.success(user));
    }

    public ResponseEntity<ApiResponse<String>> resetPassword(User user) {
        try {
            userMapper.resetPassword(user);
            return ResponseEntity.ok(ApiResponse.success("重置密码成功"));
        }
        catch (Exception e) {
            return ResponseEntity.status(500).body(ApiResponse.error(500,"服务器内部错误"));
        }
    }
}